﻿using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;

namespace JwtBearer;

public class JwtService : IJwtService
{
    private readonly JwtSecurityTokenHandler _tokenHandler;
    private readonly IOptions<JwtBearerOptions> _options;

    public JwtService(JwtSecurityTokenHandler tokenHandler, IOptions<JwtBearerOptions> options)
    {
        _tokenHandler = tokenHandler;
        _options = options;
    }

    public Task<string> GenerateTokenAsync(string username)
    {
        var key = _options.Value.Key;
        var issuer = _options.Value.Issuer;
        var audience = _options.Value.Audience;
        var expireMinutes = _options.Value.ExpireMinutes;

        var credential = new SigningCredentials(
            new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key)) /* key */,
            SecurityAlgorithms.HmacSha256 /*指定算法*/);

        var claims = new Claim[]
        {
            new Claim(ClaimTypes.Name, username)
        };
        var securityToken = new JwtSecurityToken(
            issuer: issuer,
            audience: audience,
            claims: claims,
            expires: DateTime.Now.AddHours(1), // 1小时后过期
            signingCredentials: credential);
        var token = _tokenHandler.WriteToken(securityToken);
        return Task.FromResult(token);
    }
}